<template>
  <div class="backup-manager">
    <div class="backup-header">
      <h2>数据库备份管理</h2>
      <div class="backup-actions">
        <button @click="createBackup" class="btn btn-primary" :disabled="isCreating">
          <i class="fa-solid fa-download"></i>
          {{ isCreating ? '创建中...' : '立即备份' }}
        </button>
        <button @click="refreshBackups" class="btn btn-secondary">
          <i class="fa-solid fa-refresh"></i>
          刷新
        </button>
      </div>
    </div>

    <!-- 备份统计 -->
    <div class="backup-stats">
      <div class="stat-card">
        <div class="stat-number">{{ stats.totalBackups }}</div>
        <div class="stat-label">总备份数</div>
      </div>
      <div class="stat-card">
        <div class="stat-number">{{ formatSize(stats.totalSize) }}</div>
        <div class="stat-label">总大小</div>
      </div>
      <div class="stat-card">
        <div class="stat-number">{{ stats.newestBackup ? formatDate(stats.newestBackup) : '无' }}</div>
        <div class="stat-label">最新备份</div>
      </div>
    </div>

    <!-- 标签页 -->
    <div class="backup-tabs">
      <button 
        @click="activeTab = 'local'" 
        class="tab-btn"
        :class="{ active: activeTab === 'local' }"
      >
        本地备份
      </button>
      <button 
        @click="activeTab = 'cloud'" 
        class="tab-btn"
        :class="{ active: activeTab === 'cloud' }"
      >
        云端备份
      </button>
      <button 
        @click="activeTab = 'schedule'" 
        class="tab-btn"
        :class="{ active: activeTab === 'schedule' }"
      >
        定时备份
      </button>
    </div>

    <!-- 本地备份列表 -->
    <div v-if="activeTab === 'local'" class="backup-section">
      <div class="section-header">
        <h3>本地备份文件</h3>
        <button @click="cleanupBackups" class="btn btn-sm btn-warning">
          清理旧备份
        </button>
      </div>
      
      <div v-if="localBackups.length === 0" class="empty-state">
        暂无备份文件
      </div>
      
      <div v-else class="backup-list">
        <div v-for="backup in localBackups" :key="backup.filename" class="backup-item">
          <div class="backup-info">
            <div class="backup-name">{{ backup.filename }}</div>
            <div class="backup-meta">
              <span>{{ formatDate(backup.created_at) }}</span>
              <span>{{ formatSize(backup.size) }}</span>
              <span class="backup-type" :class="backup.type">{{ getTypeLabel(backup.type) }}</span>
            </div>
          </div>
          <div class="backup-actions">
            <button @click="downloadBackup(backup.filename)" class="btn btn-sm btn-info">
              下载
            </button>
            <button @click="restoreBackup(backup.filename)" class="btn btn-sm btn-success">
              恢复
            </button>
            <button @click="deleteBackup(backup.filename)" class="btn btn-sm btn-danger">
              删除
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 云端备份配置 -->
    <div v-if="activeTab === 'cloud'" class="backup-section">
      <div class="cloud-config">
        <h3>云存储配置</h3>
        <div class="config-form">
          <div class="form-group">
            <label>云存储提供商:</label>
            <select v-model="cloudConfig.provider">
              <option value="">请选择</option>
              <option value="aliyun">阿里云OSS</option>
              <option value="tencent">腾讯云COS</option>
            </select>
          </div>
          
          <!-- 阿里云OSS配置 -->
          <div v-if="cloudConfig.provider === 'aliyun'" class="provider-config">
            <div class="form-group">
              <label>Region:</label>
              <input v-model="cloudConfig.aliyun.region" placeholder="如: oss-cn-hangzhou" />
            </div>
            <div class="form-group">
              <label>AccessKeyId:</label>
              <input v-model="cloudConfig.aliyun.accessKeyId" type="password" />
            </div>
            <div class="form-group">
              <label>AccessKeySecret:</label>
              <input v-model="cloudConfig.aliyun.accessKeySecret" type="password" />
            </div>
            <div class="form-group">
              <label>Bucket:</label>
              <input v-model="cloudConfig.aliyun.bucket" />
            </div>
          </div>
          
          <!-- 腾讯云COS配置 -->
          <div v-if="cloudConfig.provider === 'tencent'" class="provider-config">
            <div class="form-group">
              <label>Region:</label>
              <input v-model="cloudConfig.tencent.region" placeholder="如: ap-guangzhou" />
            </div>
            <div class="form-group">
              <label>SecretId:</label>
              <input v-model="cloudConfig.tencent.secretId" type="password" />
            </div>
            <div class="form-group">
              <label>SecretKey:</label>
              <input v-model="cloudConfig.tencent.secretKey" type="password" />
            </div>
            <div class="form-group">
              <label>Bucket:</label>
              <input v-model="cloudConfig.tencent.bucket" placeholder="如: bucket-name-123456" />
            </div>
          </div>
          
          <button @click="saveCloudConfig" class="btn btn-primary">保存配置</button>
        </div>
      </div>
      
      <!-- 云端备份列表 -->
      <div class="cloud-backups">
        <h3>云端备份文件</h3>
        <button @click="listCloudBackups" class="btn btn-secondary">刷新云端列表</button>
        
        <div v-if="cloudBackups.length === 0" class="empty-state">
          暂无云端备份文件
        </div>
        
        <div v-else class="backup-list">
          <div v-for="backup in cloudBackups" :key="backup.remotePath" class="backup-item">
            <div class="backup-info">
              <div class="backup-name">{{ backup.filename }}</div>
              <div class="backup-meta">
                <span>{{ formatDate(backup.uploadTime) }}</span>
                <span>{{ formatSize(backup.size) }}</span>
                <span v-if="backup.url" class="backup-url">
                  <a :href="backup.url" target="_blank">查看</a>
                </span>
              </div>
            </div>
            <div class="backup-actions">
              <button @click="downloadFromCloud(backup)" class="btn btn-sm btn-info">
                下载
              </button>
              <button @click="deleteFromCloud(backup.remotePath)" class="btn btn-sm btn-danger">
                删除
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 定时备份配置 -->
    <div v-if="activeTab === 'schedule'" class="backup-section">
      <div class="schedule-config">
        <h3>定时备份设置</h3>
        <div class="form-group">
          <label>备份频率:</label>
          <select v-model="scheduleConfig.preset">
            <option value="">自定义</option>
            <option v-for="(expr, name) in presets" :key="name" :value="name">
              {{ getPresetLabel(name) }}
            </option>
          </select>
        </div>
        
        <div v-if="!scheduleConfig.preset" class="form-group">
          <label>Cron表达式:</label>
          <input v-model="scheduleConfig.cronExpression" placeholder="0 2 * * *" />
          <small>格式: 分 时 日 月 周 (例如: 0 2 * * * 表示每天凌晨2点)</small>
        </div>
        
        <div class="form-group">
          <label>
            <input type="checkbox" v-model="scheduleConfig.autoUpload" />
            自动上传到云端
          </label>
        </div>
        
        <div class="form-group">
          <label>保留备份数量:</label>
          <input v-model.number="scheduleConfig.maxBackups" type="number" min="1" max="50" />
        </div>
        
        <button @click="startScheduledBackup" class="btn btn-primary">启动定时备份</button>
      </div>
      
      <!-- 活动任务 -->
      <div class="active-tasks">
        <h3>活动任务</h3>
        <div v-if="scheduledTasks.length === 0" class="empty-state">
          暂无活动任务
        </div>
        
        <div v-else class="task-list">
          <div v-for="task in scheduledTasks" :key="task.name" class="task-item">
            <div class="task-info">
              <div class="task-name">{{ task.name }}</div>
              <div class="task-status" :class="{ running: task.running }">
                {{ task.running ? '运行中' : '已停止' }}
              </div>
            </div>
            <button @click="stopScheduledTask(task.name)" class="btn btn-sm btn-danger">
              停止
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'

const activeTab = ref('local')
const localBackups = ref([])
const cloudBackups = ref([])
const scheduledTasks = ref([])
const presets = ref({})
const stats = ref({
  totalBackups: 0,
  totalSize: 0,
  newestBackup: null
})

const isCreating = ref(false)

const cloudConfig = ref({
  provider: '',
  aliyun: {
    region: '',
    accessKeyId: '',
    accessKeySecret: '',
    bucket: ''
  },
  tencent: {
    region: '',
    secretId: '',
    secretKey: '',
    bucket: ''
  }
})

const scheduleConfig = ref({
  preset: '',
  cronExpression: '',
  autoUpload: false,
  maxBackups: 10
})

// 获取本地备份列表
const fetchLocalBackups = async () => {
  try {
    const response = await fetch('/api/backup/listBackups')
    const data = await response.json()
    if (data.success) {
      localBackups.value = data.backups
      updateStats()
    }
  } catch (error) {
    console.error('获取本地备份失败:', error)
  }
}

// 创建备份
const createBackup = async () => {
  isCreating.value = true
  try {
    const response = await fetch('/api/backup/createBackup', {
      method: 'POST'
    })
    const data = await response.json()
    if (data.success) {
      alert('备份创建成功')
      await fetchLocalBackups()
    }
  } catch (error) {
    console.error('创建备份失败:', error)
    alert('创建备份失败')
  } finally {
    isCreating.value = false
  }
}

// 下载备份
const downloadBackup = (filename) => {
  window.open(`/api/backup/downloadBackup?filename=${encodeURIComponent(filename)}`)
}

// 恢复备份
const restoreBackup = async (filename) => {
  if (!confirm(`确定要恢复备份 "${filename}" 吗？当前数据将被覆盖。`)) {
    return
  }
  
  try {
    const response = await fetch('/api/backup/restoreBackup', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ filename })
    })
    const data = await response.json()
    if (data.success) {
      alert(`备份恢复成功！已创建安全备份: ${data.safetyBackup}`)
    }
  } catch (error) {
    console.error('恢复备份失败:', error)
    alert('恢复备份失败')
  }
}

// 删除备份
const deleteBackup = async (filename) => {
  if (!confirm(`确定要删除备份 "${filename}" 吗？`)) {
    return
  }
  
  try {
    const response = await fetch('/api/backup/deleteBackup', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ filename })
    })
    const data = await response.json()
    if (data.success) {
      alert('备份删除成功')
      await fetchLocalBackups()
    }
  } catch (error) {
    console.error('删除备份失败:', error)
    alert('删除备份失败')
  }
}

// 清理旧备份
const cleanupBackups = async () => {
  if (!confirm('确定要清理旧备份吗？将只保留最新的10个备份。')) {
    return
  }
  
  try {
    // 这里需要调用清理API，暂时用刷新代替
    await fetchLocalBackups()
    alert('清理完成')
  } catch (error) {
    console.error('清理备份失败:', error)
  }
}

// 刷新备份列表
const refreshBackups = async () => {
  await fetchLocalBackups()
}

// 获取云端备份列表
const listCloudBackups = async () => {
  if (!cloudConfig.value.provider) {
    alert('请先配置云存储')
    return
  }
  
  try {
    const response = await fetch('/api/backup/listCloudBackups', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ cloudConfig: cloudConfig.value })
    })
    const data = await response.json()
    if (data.success) {
      cloudBackups.value = data.backups
    }
  } catch (error) {
    console.error('获取云端备份失败:', error)
  }
}

// 获取定时任务
const fetchScheduledTasks = async () => {
  try {
    const response = await fetch('/api/backup/getScheduledTasks')
    const data = await response.json()
    if (data.success) {
      scheduledTasks.value = data.tasks
      presets.value = data.presets
    }
  } catch (error) {
    console.error('获取定时任务失败:', error)
  }
}

// 启动定时备份
const startScheduledBackup = async () => {
  const cronExpression = scheduleConfig.value.preset 
    ? presets.value[scheduleConfig.value.preset]
    : scheduleConfig.value.cronExpression
  
  if (!cronExpression) {
    alert('请选择备份频率或输入Cron表达式')
    return
  }
  
  try {
    const response = await fetch('/api/backup/scheduleBackup', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        cronExpression,
        options: {
          autoUpload: scheduleConfig.value.autoUpload,
          cloudConfig: scheduleConfig.value.autoUpload ? cloudConfig.value : null,
          maxBackups: scheduleConfig.value.maxBackups
        }
      })
    })
    const data = await response.json()
    if (data.success) {
      alert('定时备份任务已启动')
      await fetchScheduledTasks()
    }
  } catch (error) {
    console.error('启动定时备份失败:', error)
    alert('启动定时备份失败')
  }
}

// 停止定时任务
const stopScheduledTask = async (taskName) => {
  try {
    const response = await fetch('/api/backup/stopScheduledBackup', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ taskName })
    })
    const data = await response.json()
    if (data.success) {
      alert('定时任务已停止')
      await fetchScheduledTasks()
    }
  } catch (error) {
    console.error('停止定时任务失败:', error)
  }
}

// 更新统计信息
const updateStats = () => {
  stats.value.totalBackups = localBackups.value.length
  stats.value.totalSize = localBackups.value.reduce((sum, backup) => sum + backup.size, 0)
  stats.value.newestBackup = localBackups.value[0]?.created_at || null
}

// 格式化日期
const formatDate = (dateString) => {
  return new Date(dateString).toLocaleString('zh-CN')
}

// 格式化大小
const formatSize = (bytes) => {
  if (bytes < 1024) return bytes + ' B'
  if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB'
  return (bytes / (1024 * 1024)).toFixed(1) + ' MB'
}

// 获取类型标签
const getTypeLabel = (type) => {
  const labels = {
    manual: '手动',
    auto: '自动',
    scheduled: '定时',
    before_restore: '恢复前'
  }
  return labels[type] || type
}

// 获取预设标签
const getPresetLabel = (preset) => {
  const labels = {
    hourly: '每小时',
    daily: '每天',
    weekly: '每周',
    monthly: '每月',
    every_6h: '每6小时',
    every_12h: '每12小时',
    workdays: '工作日',
    weekends: '周末'
  }
  return labels[preset] || preset
}

onMounted(() => {
  fetchLocalBackups()
  fetchScheduledTasks()
})
</script>

<style scoped>
.backup-manager {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.backup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.backup-header h2 {
  margin: 0;
  color: #333;
}

.backup-actions {
  display: flex;
  gap: 12px;
}

.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  display: flex;
  align-items: center;
  gap: 6px;
}

.btn-primary {
  background-color: #007bff;
  color: white;
}

.btn-secondary {
  background-color: #6c757d;
  color: white;
}

.btn-success {
  background-color: #28a745;
  color: white;
}

.btn-danger {
  background-color: #dc3545;
  color: white;
}

.btn-warning {
  background-color: #ffc107;
  color: #212529;
}

.btn-info {
  background-color: #17a2b8;
  color: white;
}

.btn-sm {
  padding: 4px 8px;
  font-size: 12px;
}

.btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.backup-stats {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
  margin-bottom: 24px;
}

.stat-card {
  background: white;
  padding: 20px;
  border-radius: 8px;
  border: 1px solid #e1e5e9;
  text-align: center;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #007bff;
  margin-bottom: 8px;
}

.stat-label {
  color: #6c757d;
  font-size: 14px;
}

.backup-tabs {
  display: flex;
  border-bottom: 1px solid #e1e5e9;
  margin-bottom: 24px;
}

.tab-btn {
  padding: 12px 24px;
  border: none;
  background: none;
  cursor: pointer;
  border-bottom: 2px solid transparent;
  transition: all 0.2s;
}

.tab-btn.active {
  color: #007bff;
  border-bottom-color: #007bff;
}

.backup-section {
  background: white;
  padding: 24px;
  border-radius: 8px;
  border: 1px solid #e1e5e9;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h3 {
  margin: 0;
  color: #333;
}

.empty-state {
  text-align: center;
  padding: 40px;
  color: #6c757d;
}

.backup-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.backup-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border: 1px solid #e1e5e9;
  border-radius: 6px;
  background: #f8f9fa;
}

.backup-info {
  flex: 1;
}

.backup-name {
  font-weight: 500;
  margin-bottom: 4px;
}

.backup-meta {
  display: flex;
  gap: 16px;
  font-size: 12px;
  color: #6c757d;
}

.backup-type {
  padding: 2px 6px;
  border-radius: 3px;
  font-size: 11px;
}

.backup-type.manual {
  background-color: #007bff;
  color: white;
}

.backup-type.auto {
  background-color: #28a745;
  color: white;
}

.backup-type.scheduled {
  background-color: #ffc107;
  color: #212529;
}

.backup-actions {
  display: flex;
  gap: 8px;
}

.cloud-config {
  margin-bottom: 32px;
}

.config-form {
  background: #f8f9fa;
  padding: 20px;
  border-radius: 6px;
}

.form-group {
  margin-bottom: 16px;
}

.form-group label {
  display: block;
  margin-bottom: 6px;
  font-weight: 500;
}

.form-group input,
.form-group select {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.form-group small {
  display: block;
  margin-top: 4px;
  color: #6c757d;
  font-size: 12px;
}

.provider-config {
  background: white;
  padding: 16px;
  border-radius: 4px;
  margin-top: 12px;
}

.cloud-backups {
  margin-top: 24px;
}

.backup-url a {
  color: #007bff;
  text-decoration: none;
}

.backup-url a:hover {
  text-decoration: underline;
}

.task-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.task-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border: 1px solid #e1e5e9;
  border-radius: 6px;
  background: #f8f9fa;
}

.task-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.task-status {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  background-color: #dc3545;
  color: white;
}

.task-status.running {
  background-color: #28a745;
}
</style>
